<template>
  <!-- 添加管理员 -->
  <el-form :model="admin" class="form-box">

    <el-form-item prop="adminname">
      <el-input disabled v-model="admin.adminname" placeholder="姓名" />
    </el-form-item>

    <el-form-item prop="password">
      <el-input v-model="admin.password" placeholder="新密码" />
    </el-form-item>

    <el-form-item>
      <el-select v-model="admin.role">
        <el-option value="1" label="超级管理员" />
        <el-option value="2" label="管理员" />
        <el-option value="3" label="轮播图维护" />
        <el-option value="4" label="商品管理员" />
      </el-select>
    </el-form-item>
    <!-- 
      树形结构的default-checked-keys属性：当组件el-tree初次渲染时，就需要传入数据，其它时机传入的数据不起作用。
     -->
    <el-tree ref="treeRef" :data="data" show-checkbox default-expand-all node-key="id" highlight-current />
    <el-form-item>
      <el-button type="primary" @click="editAdmin">修改</el-button>
      <el-button>取消</el-button>
    </el-form-item>

  </el-form>

</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { getAdminDetailApi, updateAdminApi } from "@/api/admin.ts";
import type { AxiosResponse } from "axios";
import type { IAdmin } from "@/myTypes";
import { data } from "@/grants/data.ts";
import { ElTree,ElMessage } from "element-plus";

// 声明属性：
interface IProps {
  adminname: string,
  password: string
}
const props = defineProps<IProps>();

interface IEmits {
  (e: 'cancel'): void,
  (e: "ok"): void
}

const emit = defineEmits<IEmits>()


const treeRef = ref<InstanceType<typeof ElTree>>();

// 定义管理员的信息：
const admin = reactive<IAdmin>({
  "adminid": "",
  "adminname": "",
  "password": "",
  "role": "",
  "checkedKeys": []
});

// 获取该管理员的数据：
function getAdminDetail() {
  getAdminDetailApi(props.adminname)
    .then((res: AxiosResponse) => {
      // 后端响应回来时，组件已经初次渲染完毕？？
      if (res.data.code === "200") {
        admin.adminid = res.data.data[0].adminid;
        admin.adminname = res.data.data[0].adminname;
        admin.role = String(res.data.data[0].role);
        admin.checkedKeys = res.data.data[0].checkedKeys;
        // admin.password = props.password;
        // 调用el-tree组件的方法 setCheckedKeys()让el-tree对应的节点处于选中状态。 ps：这个方法就是el-tree内部用expose对外开放的方式。
        treeRef.value?.setCheckedKeys(admin.checkedKeys);
      }
    })
}

getAdminDetail();


// 修改管理员
function editAdmin() {

  let arr = treeRef.value!.getCheckedKeys(false);
  treeRef.value!.getHalfCheckedKeys().forEach(item => {
    if (!arr.includes(item)) {
      arr.push(item);
    }
  });

  updateAdminApi({
    adminname: admin.adminname,
    password: admin.password,
    role: admin.role,
    checkedKeys: arr
  })
    .then((res: AxiosResponse) => {
      if (res.data.code === "200") {
        ElMessage.success("修改成功！");
        emit("ok");
      }
    })
}


</script>

<style>

</style>